package com.qiwo.common.controller;

import com.qiwo.common.base.AdminBaseController;
import com.qiwo.common.type.EnumErrorCode;
import com.qiwo.common.utils.Result;
import com.qiwo.common.utils.UploadProperties;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.Calendar;
import java.util.UUID;

/**
 * Copyright
 *
 * @Author:chenwenchao
 * @Date:2018/10/23 0023
 * Description:
 */

@Controller
@RequestMapping("/common/sysFile")
public class FileController extends AdminBaseController {

    @Resource
    private UploadProperties uploadProperties;

    @PostMapping("/imgupload")
    @ResponseBody
    Result<String> imgupload(HttpServletRequest request, @RequestParam("file")MultipartFile file) {
        //可以从页面传参数过来
        System.out.println("name====="+request.getParameter("name"));
        String outFilePath=  uploadProperties.getBasePath();
        File dir=new File(outFilePath);
        if(!dir.exists()){
            dir.mkdir();
        }
        String imagename="";
        //这里可以支持多文件上传
        if(file!=null) {
            BufferedOutputStream bw = null;
            try {
                String fileName = file.getOriginalFilename();
                String ramdomName= UUID.randomUUID().toString();
                Calendar now = Calendar.getInstance();
                String dayPath=now.get(Calendar.YEAR)+"/"+(now.get(Calendar.MONTH) + 1) ;
                //判断是否有文件且是否为图片文件
                if(fileName!=null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {
                    //创建输出文件对象
                    File outFile = new File(uploadProperties.getBasePath() + "/"+ dayPath+"/"+ ramdomName+ getFileType(fileName));
                    //拷贝文件到输出文件对象
                    FileUtils.copyInputStreamToFile(file.getInputStream(), outFile);
                    return Result.ok("/"+dayPath+"/"+outFile.getName());
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.build(EnumErrorCode.FileUploadGetBytesError.getCode(),
                        EnumErrorCode.FileUploadGetBytesError.getMsg());
            } finally {
                try {
                    if(bw!=null) {bw.close();}
                } catch (IOException e) {
                    e.printStackTrace();
                    return Result.build(EnumErrorCode.FileUploadGetBytesError.getCode(),
                            EnumErrorCode.FileUploadGetBytesError.getMsg());
                }
            }
        }
        return Result.build(EnumErrorCode.FileUploadGetBytesError.getCode(),
                EnumErrorCode.FileUploadGetBytesError.getMsg());
    }

    /**
     * 判断文件是否为图片文件
     * @param fileName
     * @return
     */
    private Boolean isImageFile(String fileName) {
        String [] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp",".mp4"};
        if(fileName==null) {return false;}
        fileName = fileName.toLowerCase();
        for(String type : img_type) {
            if(fileName.endsWith(type)) {return true;}
        }
        return false;
    }

    /**
     * 获取文件后缀名
     * @param fileName
     * @return
     */
    private String getFileType(String fileName) {
        if(fileName!=null && fileName.indexOf(".")>=0) {
            return fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        return "";
    }
}
